<template>
    <div class="content_panel project_modules amount_remission_wait_list">
        <div class="content_panel_top">
            <h3 class="panel_title">
                <span>{{$t('collection.autoSend')}}</span>
            </h3>
            <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                <el-row>
                    <el-col :span="6">
                        <el-form-item prop="type">
                            <el-select v-model="form.type" clearable :placeholder="$t('collection.messageType')" style="width: 100%"><!--消息类型-->
                                <el-option key="1" :label="$t('collection.sms')" :value="1"><!--短信--></el-option>
                                <el-option key="2" :label="$t('collection.email')" :value="2"><!--邮件--></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="appName" label="">
                            <select-app-list v-model="form.appName" :placeholder="$t('system.appName')"></select-app-list><!--app名称-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="overdueDay">
                            <el-input v-model="form.overdueDay" :placeholder="$t('common.overdueDays')" clearable></el-input><!--逾期天数-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="templateName">
                            <el-input v-model="form.templateName" :placeholder="$t('collection.templateName')" clearable></el-input><!--模板名称-->
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item prop="isEnabled">
                            <el-select v-model="form.isEnabled" clearable :placeholder="$t('common.status')" style="width: 100%"><!--状态-->
                                <el-option key="1" :label="$t('collection.activated')" value="1"><!--已启用--></el-option>
                                <el-option key="0" :label="$t('collection.closed')" value="0"><!--已关闭--></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="remark">
                            <el-input v-model="form.remark" :placeholder="$t('common.remark')" clearable></el-input><!--备注-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-button @click="search" type="primary">{{ $t('common.search') }}</el-button>
                        <el-button @click="addHandler('add')" type="primary">{{ $t('common.add') }}</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div><!--content_panel_top-->

        <div class="module_content">
            <div class="content_panel project_modules">
                <div class="table_list">
                    <el-table ref="table" :data="tableData" style="width: 100%;" :max-height="tableMaxHeight" :highlight-current-row="true">
                        <el-table-column prop="type" :label="$t('collection.messageType')" min-width="120"><!--消息类型-->
                            <template slot-scope="{ row }">{{ row.type | switchMessageType }}</template>
                        </el-table-column>
                        <el-table-column prop="overdueDay" :label="$t('common.overdueDays')" min-width="120"></el-table-column><!--逾期天数-->
                        <el-table-column align="left" :label="$t('system.appName')" prop="appName" width="160"></el-table-column><!--APP名称-->
                        <el-table-column prop="templateName" :label="$t('collection.templateName')" min-width="300">
                            <template slot-scope="{ row }"><el-button @click="checkTemplate(row)" type="text">{{ row.templateName }}</el-button></template>
                        </el-table-column><!--模板名称-->
                        <el-table-column prop="showSendDate" :label="$t('collection.sendTime')" min-width="140"><!--发送时间-->
                            <template slot-scope="{ row }">{{ (row.showSendDate).substring(0,2) + ':' + (row.showSendDate).substring(2) }}:00</template>
                        </el-table-column>
                        <el-table-column :label="$t('common.remark')" prop="remark" min-width="220" :show-overflow-tooltip="true"></el-table-column><!--备注-->
                        <el-table-column prop="isEnabled" :label="$t('common.status')" min-width="120"><!--状态-->
                            <template slot-scope="{ row }">{{ row.isEnabled | switchStatus }}</template>
                        </el-table-column>
                        <el-table-column prop="updateTime" :label="$t('collection.lastEdit')" min-width="180"><!--最近一次编辑-->
                            <template slot-scope="{ row }">{{ row.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                        </el-table-column>
                        <el-table-column :label="$t('common.operation')" min-width="180">
                            <template slot-scope="scope">
                                <el-button @click="addHandler('edit',scope.row)" type="text">{{ $t('finance.edit') }}</el-button><!--编辑-->
                                <el-button v-if="scope.row.isEnabled === 1" @click="operateHandler('0',scope.row)" type="text">{{ $t('common.close') }}</el-button><!--关闭-->
                                <el-button v-if="scope.row.isEnabled === 0" @click="operateHandler('1',scope.row)" type="text">{{ $t('collection.startUse') }}</el-button><!--启用-->
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--分页组件-->
                    <pagination @pageChange="pageChange" :page="page"><!--分页组件--></pagination>
                </div>
            </div>
        </div>

        <!--新增&编辑弹窗-->
        <el-dialog :visible.sync="addDialog.isVisible" :title="$t('collection.messageConfig')" width="600px" class="operate-dialog" :close-on-click-modal="false">
            <div class="content">
                <el-form ref="addDialog.form" :model="addDialog.form" :rules="addDialog.rules" :inline="false" label-position="top" class="module_form">
                    <el-form-item v-if="addDialog.type === 'add'" prop="appName" :label="$t('system.appName')"><!--appName-->
                        <el-select v-model="addDialog.form.appName" :placeholder="$t('verify.plsChoose')" clearable style="width:100%;">
                            <el-option v-for="item in appList" :key="item.id" :value="item.name" :label="item.name" ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('collection.templateType')" prop="type">
                        <el-select v-model="addDialog.form.type" @change="getTemplateData" clearable :placeholder="$t('verify.plsChoose')" style="width: 100%"><!--消息类型-->
                            <el-option key="1" :label="$t('collection.sms')" :value="1"><!--短信--></el-option>
                            <!--<el-option v-if="!addDialog.form.sendTarget || addDialog.form.sendTarget === 1" key="2" :label="$t('collection.email')" :value="2">&lt;!&ndash;邮件&ndash;&gt;</el-option>-->
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('common.overdueDays')" prop="overdueDay"><!--逾期天数-->
                        <el-input-number v-model="addDialog.form.overdueDay" :min="-10" :max="999" :placeholder="$t('verify.plsInput')" style="width: 100%"></el-input-number>
                    </el-form-item>
                    <el-form-item v-if="addDialog.type === 'edit'" prop="appName" :label="$t('system.appName')"><!--appName-->
                        <el-select v-model="addDialog.form.appName" :placeholder="$t('verify.plsChoose')" clearable style="width:100%;">
                            <el-option v-for="item in appList" :key="item.id" :value="item.name" :label="item.name" ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="addDialog.form.type" :label="$t('collection.chooseTemplate')" prop="template"><!--选择模版-->
                        <el-select v-model="addDialog.form.template" @change="getTemplate" clearable :placeholder="$t('verify.plsChoose')" style="width: 100%">
                            <el-option v-for="(item, $index) in addDialog.templateDataByAppName" :key="$index" :value="item.id" :label="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-button v-if="addDialog.form.template" @click="checkTemplate('')" type="text">{{ $t('collection.checkTemplateContent') }}</el-button><!--查看模版内容-->
                    <el-form-item v-if="addDialog.form.type" :label="$t('collection.sendObject')" prop="sendTarget">
                        <el-select v-model="addDialog.form.sendTarget" clearable :placeholder="$t('verify.plsChoose')" style="width: 100%"><!--发送对象-->
                            <el-option key="1" :label="$t('collection.self')" :value="1"><!--本人--></el-option>
                            <el-option v-if="addDialog.form.type === 1" key="2" :label="$t('common.contacts')" :value="2"><!--联系人--></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('collection.sendTime')" prop="hour" style="width:150px;display: inline-block"><!--发送时间-->
                        <el-select v-model="addDialog.form.hour" clearable :placeholder="$t('verify.plsChoose')" style="width: 100%">
                            <el-option v-for="(item, $index) in addDialog.hourData" :key="$index" :value="item" :label="item"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="minute" style="width:150px;display: inline-block"><!--发送时间-->
                        <el-select v-model="addDialog.form.minute" clearable :placeholder="$t('verify.plsChoose')" style="width: 100%">
                            <el-option v-for="(item, $index) in addDialog.minuteData" :key="$index" :value="item" :label="item"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('common.remark')" prop="remark"><!--备注-->
                        <el-input v-model="addDialog.form.remark" maxlength="200" :rows="3" type="textarea" :placeholder="$t('verify.underXWords',{x: '200'})"></el-input>
                    </el-form-item>
                    <div class="btn-box">
                        <el-button @click="addDialog.isVisible = false" type="primary">{{ $t('common.cancel') }}</el-button>
                        <el-button @click="addSubmit" type="primary">{{ $t('common.confirm') }}</el-button>
                    </div>
                </el-form>
            </div>
        </el-dialog>

        <!--查看模版弹窗-->
        <el-dialog :visible.sync="addDialog.isVisibleTemplate" :title="$t('common.check') + '-' + (addDialog.form.type === 2 ? $t('collection.mailTemplate') : $t('collection.smsTemplate'))"  width="900px" class="template-dialog">
            <div class="title">{{ addDialog.selectedTemplate.templateName }}</div>
            <div class="content">
                <div v-if="addDialog.form.type === 1">{{ addDialog.selectedTemplate.content }}</div>
                <div v-if="addDialog.form.type === 2" v-html="addDialog.selectedTemplate.content"></div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import Pagination from '@/components/pagination';
    import mixin from '@/service/mixin';
    import AlertDialog from '@/components/alert-dialog';
    import SelectAppList from '@/components/select-app-list';

    let that = null;
    export default {
        name: 'collection-messageManage-autoSend',
        components: {
            Pagination,
            AlertDialog,
            SelectAppList
        },
        mixins: [mixin],
        data() {
            const checkOverdueDays = (rule, value, callback) => {
               if(value > 999 || value < -10) {
                    return callback(this.$t('collection.plsInputRightOverday'));
                }
                else {
                    callback();
                }
            };
            return {
                tableData: [],
                appList: [],
                form: {
                    type: '',
                    appName: '',
                    overdueDay: '',
                    templateName: '',
                    isEnabled: '',
                    remark: '',
                },
                rules: {
                    overdueDay:[
                        {pattern: /^-?[0-9]\d*$/, message: this.$t('verify.inputInteger')},
                        { validator: checkOverdueDays, trigger: 'blur' }
                    ]
                },
                addDialog: {
                    isVisible: false,
                    type: '',
                    form: {
                        appName: '',
                        type: '',
                        overdueDay: '',
                        template: '',
                        sendTarget: '',
                        hour: '',
                        minute: '',
                        remark: '',
                    },
                    rules: { 
                        appName: [
                            {required: true, message: this.$t('verify.plsChoose')},
                        ],
                        type: [
                            {required: true, message: this.$t('verify.plsChoose')},
                        ],
                        overdueDay: [
                            {required: true, message: this.$t('collection.plsInputRightOverday')},
                            {pattern: /^-?[0-9]\d*$/, message: this.$t('collection.plsInputRightOverday'), trigger: 'change'},
                            { validator: checkOverdueDays, trigger: 'change' }
                        ],
                        template: [
                            {required: true, message: this.$t('verify.plsChoose')},
                        ],
                        sendTarget: [
                            {required: true, message: this.$t('verify.plsChoose')},
                        ],
                        hour: [
                            {required: true, message: this.$t('verify.plsChoose')},
                        ],
                        minute: [
                            {required: true, message: this.$t('verify.plsChoose')},
                        ],
                    },
                    templateData: [],
                    templateDataByAppName: [],
                    hourData: [],
                    minuteData: [],
                    isVisibleTemplate: false,
                    selectedTemplate: {
                        templateId: '',
                        templateNid: '',
                        templateName: '',
                        content: '',
                    },
                }
            };
        },
        watch:{
            "addDialog.form.appName" :function(val) {
                if (val) {
                    this.filterTemplateByAppName();
                    let form = this.addDialog.form;
                    //判断当前选择的模板是否是对应app下的
                    let result = this.addDialog.templateDataByAppName.some((item, index) => {
                        return item.id == form.template;
                    })
                    if (form.template && !result) {                       
                        form.template = '';
                    }
                }
            },
        },
        methods: {
            // 获取列表数据
            getTableData(page = this.page) {
                const form = this.form;
                const params = {
                    type: form.type,
                    appName: form.appName,
                    overdueDay: form.overdueDay,
                    templateName: form.templateName,
                    isEnabled: form.isEnabled,
                    remark: form.remark,
                    page: {
                        pageNo: page.currentPage,
                        pageSize: this.page.pageSize
                    }
                };
                this.$api.collection.listPageConfig(params).then(res => {
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.tableData = data.resultData;
                        this.setPage(data.page, this.page);
                        //防止类似总共21条数据，第21条操作后变成20条数据，但请求页数依旧是第2页
                        if (this.tableData.length == 0 && page.currentPage > 1) {
                            this.getTableData({currentPage: page.currentPage - 1});
                        }
                    }
                    this.tableMaxHeight = document.body.clientHeight - 265;
                });
            },
            search() {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        this.getTableData();
                    }
                })
            },
            operateHandler(type,row) {
                const params = {
                    id: row.id,
                    isEnabled: type
                };
                this.$api.collection.editConfig(params).then(res => {
                    const {status, error, msg} = res;
                    if ('1' === status && '00000000' === error) {
                        this.getTableData();
                        this.$message.success(this.$t('common.successfulOperation'));
                    }
                    else {
                        this.$message.error(msg);
                    }
                });
            },
            addHandler(type,row) {
                this.addDialog.form = {
                    appName: '',
                    type: '',
                    overdueDay: '',
                    template: '',
                    sendTarget: '',
                    hour: '',
                    minute: '',
                    remark: '',
                };
                this.addDialog.isVisible = true;
                this.$nextTick( () => {
                    this.$refs['addDialog.form'].clearValidate();
                });
                this.addDialog.type = type;
                if(type === 'edit') {
                    const params = {
                        type: row.type,
                    };
                    this.$api.collection.listTemplate(params).then(res => {
                        const {status, data, error, msg} = res;
                        if ('1' === status && '00000000' === error) {
                            this.addDialog.templateData = data;
                            this.addDialog.form = Object.assign(this.addDialog.form,row);
                            this.addDialog.form.template = row.templateId;
                            let hour = row.showSendDate.substring(0,2);
                            this.addDialog.form.hour = hour.substring(0,1) === '0' ? hour.substring(1) : hour;
                            this.addDialog.form.minute = row.showSendDate.substring(2);
                            this.getTemplate(row.templateId);
                        }
                    });
                }
                else {
                    this.addDialog.form.template = '';
                    this.addDialog.form.sendTarget = '';
                }
            },
            addSubmit() {
                this.$refs['addDialog.form'].validate((valid) => {
                    if (valid) {
                        const form = this.addDialog.form;
                        const template = this.addDialog.selectedTemplate;
                        const params = {
                            appName: form.appName,
                            type: form.type,
                            templateId: template.templateId,
                            templateNid: template.templateNid,
                            templateName: template.templateName,
                            overdueDay: form.overdueDay,
                            sendTarget: form.sendTarget,
                            sendDate: form.hour + '' + form.minute,
                            remark: form.remark
                        };
                        if(this.addDialog.type === 'add') {
                            this.$api.collection.addConfig(params).then(res => {
                                const {status, error, msg} = res;
                                if ('1' === status && '00000000' === error) {
                                    this.getTableData();
                                    this.$message.success(this.$t('common.successfulOperation'));
                                    this.addDialog.isVisible = false;
                                }
                                else {
                                    this.$message.error(msg);
                                }
                            });
                        }
                        if(this.addDialog.type === 'edit') {
                            params.id = form.id;
                            params.isEnabled = '0';
                            this.$api.collection.editConfig(params).then(res => {
                                const {status, data, error, msg} = res;
                                if ('1' === status && '00000000' === error) {
                                    this.getTableData();
                                    this.$message.success(this.$t('common.successfulOperation'));
                                    this.addDialog.isVisible = false;
                                }
                                else {
                                    this.$message.error(msg);
                                }
                            });
                        }
                    }
                })
            },
            // 获取模版数据
            getTemplateData() {
                const form = this.addDialog.form;
                const params = {
                    type: form.type,
                };
                this.$api.collection.listTemplate(params).then(res => {
                    const {status, data, error, msg} = res;
                    if ('1' === status && '00000000' === error) {
                       this.addDialog.templateData = data;
                       this.addDialog.form.template = '';
                       if (this.addDialog.form.appName) {
                           this.filterTemplateByAppName()
                       }
                    }
                });
            },
            // 获取模版内容
            getTemplate(val) {
                if(val) {
                    let data = this.addDialog.templateData.filter( item => {
                        return item.id === val
                    });
                    if(data && data.length >= 1) {
                        this.addDialog.selectedTemplate.templateId = data[0].id;
                        this.addDialog.selectedTemplate.templateNid = data[0].templateNid;
                        this.addDialog.selectedTemplate.templateName = data[0].name;
                        this.addDialog.selectedTemplate.content = data[0].content;
                    }
                    else {
                        this.$message.error(this.$t('collection.templateNotExit'));
                        this.addDialog.form.template = '';
                    }
                }
            },
            // 查看模版内容
            checkTemplate(row) {
                if(row) {
                    this.addDialog.form.type = row.type;
                    const params = {
                        type: row.type,
                    };
                    this.$api.collection.listTemplate(params).then(res => {
                        const {status, data, error, msg} = res;
                        if ('1' === status && '00000000' === error) {
                            if(data && data.length >= 1) {
                                let arr = data.filter( item => {
                                    return item.id === row.templateId
                                });
                                if(arr.length >= 1) {
                                    this.addDialog.selectedTemplate.templateName = arr[0].name;
                                    this.addDialog.selectedTemplate.content = arr[0].content;
                                    this.addDialog.isVisibleTemplate = true;
                                }
                                else {
                                    this.$message.error(this.$t('collection.templateNotExit'));
                                }
                            }
                            else {
                                this.$message.error(this.$t('collection.templateNotExit'));
                            }
                        }
                    });
                }
                else {
                    this.addDialog.isVisibleTemplate = true;
                }

            },
            initSendTimeData() {
                this.addDialog.hourData = [];
                this.addDialog.minuteData = [];
                for(var i = 0;i <= 23;i++) {
                    this.addDialog.hourData.push(i + '')
                }
                for(var i = 0;i <= 59;i++) {
                    if(i <= 9) {
                        this.addDialog.minuteData.push('0' + i)
                    }
                    else {
                        this.addDialog.minuteData.push(i)
                    }
                }
            },
            //根据选择的app名称过滤对应的短信模板
            filterTemplateByAppName() {
                const newResult = this.addDialog.templateData.filter(item => {
                    return this.addDialog.form.appName === item.appName
                });
                this.addDialog.templateDataByAppName = newResult;
            },
            getAppList() {
                const params = {
                    appListDomain: this.$storage.get('user').domain,
                };
                this.$api.systemManage.getAppListdomain(params).then((res) => {
                    const {status, data, error} = res;
                    if ('1' === status && error === '00000000') {
                        this.appList = data || [];
                    }      
                });
            },
        },
        filters: {
            //消息类型
            switchMessageType(type) {
                switch (type + '') {
                    case '1':
                        return that.$t('collection.sms');// 短信
                    case '2':
                        return that.$t('collection.email');// 邮件
                    default:
                        return type;
                }
            },
            //状态
            switchStatus(type) {
                switch (type + '') {
                    case '1':
                        return that.$t('collection.activated');// 已启用
                    case '0':
                        return that.$t('collection.closed');// 已关闭
                    default:
                        return type;
                }
            },
        },
        created() {
            that = this;
            this.getTableData();
            this.getAppList();
            this.initSendTimeData();
        }
    }
</script>
<style lang="scss">
    [data-page=collection-messageManage-autoSend] {
        .el-col {
            padding-left: 10px;
        }
        .el-table .cell, .el-table th > .cell {
            word-break: keep-all;
            word-wrap: break-word;
        }
        .operate-dialog {
            .el-form-item {
                margin-bottom:16px;
            }
            .btn-box {
                padding:20px 0 0 0;
                text-align: center;
            }
            .el-form--label-top {
                .el-form-item__label {
                    padding:0px;
                }
            }
        }
        .template-dialog {
            .title {
                font-size:18px;
                font-weight:bold;
            }
            .content {
                padding:20px 0 0 0;
                overflow: auto;
            }
        }
    }
</style>

